import { loginApi } from '@/api/user'
import router from '@/router'
import { Message } from 'element-ui'
export default {
  namespaced: true,
  state: {
    token: null,
    loginTime: 0
  },
  mutations: {
    setToken(state, token) {
      state.token = token
    },
    delToken(state) {
      state.token = null
    },
    setLogTime(state, time) {
      state.loginTime = time
    },
    delLogTime(state) {
      state.loginTime = 0
    }
  },
  actions: {
    async login({ commit }, data) {
      try {
        const res = await loginApi(data)
        console.log(res)
        if (!res.success) {
          Message.error(res.msg)
        } else {
          Message.success(res.msg)
          // 存储token
          commit('setToken', res.token)
          const time = Date.now()
          commit('setLogTime', time)
          // 跳转页面
          router.push('/')
        }
      } catch (error) {
        throw new TypeError(error)
      }
    },
    logout({ commit }) {
      commit('delToken')
      commit('delLogTime')
      // 跳转页面
      router.push('/login')
    }
  }
}

